package com.example.testat20200713

import android.media.AudioManager
import android.media.AudioRecord
import android.media.AudioTrack
import android.media.MediaRecorder
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.yanzhenjie.permission.Action
import com.yanzhenjie.permission.AndPermission
import kotlinx.android.synthetic.main.activity_main.*
import java.io.*
import java.util.jar.Manifest

class MainActivity : AppCompatActivity(), View.OnClickListener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        AndPermission.with(this@MainActivity).permission(Manifest.RECORD_AUDIO, Manifest.WRITE_EXTERNAL_STORAGE).onGranted(object : Action {
            override fun onAction(permissions: MutableList<String>?) {//同意权限
                var rootDir: File = File(AudioConfig.rootDir)
                var audioFile: File = File(AudioConfig.audioPath)
                if (!rootDir.exists()) {
                    var isDir = rootDir.mkdir()
                    if (!isDir) {
                        Toast.makeText(this@MainActivity, "创建文件夹失败", Toast.LENGTH_SHORT).show()
                        return
                    }
                }
                if (!audioFile.exists()) {
                    var isFile = audioFile.createNewFile()
                    if (isFile) {
                        Toast.makeText(this@MainActivity, "创建文件成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@MainActivity, "创建文件失败", Toast.LENGTH_SHORT).show()
                        return
                    }
                }
            }

        }).onDenied(object : Action {
            //拒绝权限
            override fun onAction(permissions: MutableList<String>?) {
                Toast.makeText(this@MainActivity, "没有权限", Toast.LENGTH_SHORT).show()
            }

        }).start()

        btn_start.setOnClickListener(this)
        btn_stop.setOnClickListener(this)
        btn_play.setOnClickListener(this)
        btn_post.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_start -> {
                AudioRecordManager.isAudioRecord = true
                var audioRecord = AudioRecordManager()
                audioRecord.start()

            }
            R.id.btn_stop -> {
                AudioRecordManager.isAudioRecord = false
            }
            R.id.btn_play -> {
                AudioTrackManager.isPaly = true
                var audioTrack = AudioTrackManager()
                audioTrack.start()

            }
            R.id.btn_post -> {
                AudioTrackManager.isPaly = false
            }
        }
    }
}

//参数配置类：
class AudioConfig {
    companion object {
        val frequency:Int = 11025 //采样率
        val audioFormat:Int = android.media.AudioFormat.ENCODING_PCM_16BIT //数据位宽
        val channelConfig:Int = android.media.AudioFormat.CHANNEL_OUT_STEREO;//双通道
        val rootDir:String = android.os.Environment.getExternalStorageDirectory().absolutePath+"/kotlinAudio";
        val audioPath:String = rootDir+"/kotlining.pcm"
    }
}

//录音：
class AudioRecordManager : Thread() {
    companion object {
        var isAudioRecord: Boolean = true
    }

    val bufferSize: Int = AudioRecord.getMinBufferSize(AudioConfig.frequency, AudioConfig.channelConfig, AudioConfig.audioFormat)
    val audioRecord: AudioRecord = AudioRecord(MediaRecorder.AudioSource.MIC, AudioConfig.frequency, AudioConfig.channelConfig, AudioConfig.audioFormat, bufferSize)
    lateinit var dataOutput: DataOutputStream
    override fun run() {
        super.run()
        val audioFile: File = File(AudioConfig.audioPath)
        if (!audioFile.exists()) {
            Log.d(">>>>>>>>", ">>>>>文件不存在>>>>")
            return
        }
        try {
            audioRecord.startRecording()
            dataOutput = DataOutputStream(BufferedOutputStream(FileOutputStream(audioFile)))
            val buffer = ShortArray(bufferSize)
            audioRecord.startRecording()
            while (isAudioRecord) {
                val bufferReadResult = audioRecord.read(buffer, 0, bufferSize)
                Log.d("cccc======", "cccc=====result:" + bufferReadResult + "////size:" + buffer.size)
                for (i in 0 until bufferReadResult) {
                    dataOutput.writeShort(buffer[i].toInt())
                }
            }
            audioRecord.stop()
            dataOutput.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

//播放：
class AudioTrackManager :Thread(){
    companion object {
        var isPaly:Boolean = true
    }
    val bufferSize: Int = android.media.AudioTrack.getMinBufferSize(AudioConfig.frequency, AudioConfig.channelConfig, AudioConfig.audioFormat)
    val buffer = ShortArray(bufferSize / 4)
    lateinit var dataInputStream: DataInputStream
    val audioTrack: AudioTrack = AudioTrack(AudioManager.STREAM_MUSIC, AudioConfig.frequency, AudioConfig.channelConfig, AudioConfig.audioFormat, bufferSize, AudioTrack.MODE_STREAM)

    override fun run() {
        super.run()
        val audioFile: File = File(AudioConfig.audioPath)
        if (!audioFile.exists()) {
            Log.d(">>>>>>>>", ">>>>>文件不存在>>>>")
            return
        }
        try {
            dataInputStream = DataInputStream(BufferedInputStream(FileInputStream(audioFile)))
            audioTrack.play()
            while (isPaly && dataInputStream.available() > 0) {
                var i:Int = 0
                while (dataInputStream.available() > 0 && i < buffer.size) {
                    buffer[i] = dataInputStream.readShort();
                    i++;
                }
                audioTrack.write(buffer, 0, buffer.size);
            }
            dataInputStream.close();
            audioTrack.release()
            audioTrack.stop()
        }catch (e:Exception){
            e.stackTrace
        }
    }
}